<template>
  <div id="sidebar-left-content" class="sidebar-left-content" :class="{ collapsed: !isExpandedLeftSidebar, expanded: isExpandedLeftSidebar }">
    <!-- 这里放置侧边栏内容 -->
    <div v-if="!isExpandedLeftSidebar" :class="{ 'sidebar-left-collapsed': !isExpandedLeftSidebar }">
      <span><img :src="$getAssetsFile('icon-filter.png')" alt="" /></span>
      <span><img :src="$getAssetsFile('icon-history.png')" alt="" /></span>
    </div>
    <div v-else :class="{ 'sidebar-left-expanded': isExpandedLeftSidebar }">
      <!-- 这里是展开后的侧边栏内容... -->
      <span class="icon-add-conversation" @click="handleAddDialogue">
        <img :src="$getAssetsFile('icon-add-white.png')" alt="" />
        新建对话
      </span>
      <span class="icon-history">
        <img :src="$getAssetsFile('icon-history-blue.png')" alt="" />
        历史记录
      </span>
      <div class="sidebar-left-history-items">
        <!-- 历史记录 start -->
        <template v-for="(item, index) in historyDialogues" :key="item.time">
          <div class="sidebar-left-history-item">
            <div>
              <span class="tit" @click="switchDialogue(item)">
                {{ item.title }}
              </span>
              <span class="time">{{ formatTime(index) }}</span>
            </div>
            <span class="sidebar-left-history-item-delete2" @click="handleDelDialogue(item.time)">
              <img :src="$getAssetsFile('btn-delete.png')" alt="" />
            </span>
          </div>
        </template>
        <!-- 历史记录 end -->
      </div>
    </div>
    <!-- 点击展开侧边栏 -->
    <div class="toggle-button" @click="handleToggleSidebar">
      <template v-if="!isExpandedLeftSidebar">
        <img :src="$getAssetsFile('icon-open.png')" alt="展开" />
      </template>
      <template v-else>
        <img :src="$getAssetsFile('icon-close.png')" alt="收起" />
      </template>
    </div>
  </div>
</template>

<script setup>
import "@/assets/styles/list.css";
import dayjs from "dayjs";
import { addDialogue, delDialogue, getAllDialogue, switchDialogue } from "@/hooks/ai-dialogue";

let isExpandedLeftSidebar = ref(false);
// 历史会话数据
let historyDialogues = ref({});
onBeforeMount(() => {
  handleInitDialogues();
});

// 从本地存储中获取当前会话和历史会话
const handleInitDialogues = (time) => {
  historyDialogues.value = getAllDialogue(time);
};

// 新建会话
const handleAddDialogue = () => {
  // 这个地方新建会话要把flag标记为true，因为不是首页跳转过来了的
  addDialogue({ flag: true });
  handleInitDialogues();
};

// 删除会话
const handleDelDialogue = (time) => {
  delDialogue(time);
  handleInitDialogues(time);
};

// 回答内容-折叠
const handleToggleSidebar = () => {
  isExpandedLeftSidebar.value = !isExpandedLeftSidebar.value;
};

// 格式化时间
const formatTime = (time) => {
  // 时间戳必须是数字，否则转换错误
  return dayjs(+time).format("YYYY-MM-DD HH:mm:ss");
};
</script>

<style lang="scss" scoped></style>
